//
//  ZLAlertAnimation.m
//  ZLAlert-OC
//
//  Created by 科大 on 2024/1/2.
//

#import "ZLAlertAnimation.h"
#import "ZLAlert.h"

@implementation ZLAlertAnimation

- (instancetype)initWith:(BOOL)isPresenting {
    self = [super init];
    if (self) {
        _isPresenting = isPresenting;
    }
    return self;
}

- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext {
    if (self.isPresenting) {
        return 0.45;
    } else {
        return 0.01;
    }
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext {
    if (self.isPresenting) {
        [self presentAnimateTransition:transitionContext];
    } else {
        [self dismissAnimateTransition:transitionContext];
    }
}

- (void)presentAnimateTransition:(id <UIViewControllerContextTransitioning>)transitionContext {
    ZLAlert *alertController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [transitionContext containerView];
    
    alertController.mainView.alpha = 0.0;
    alertController.mainView.center = alertController.view.center;
    alertController.mainView.transform = CGAffineTransformMakeScale(0.5, 0.5);
    [containerView addSubview:alertController.view];
    
    [UIView animateWithDuration:0.15 animations:^{
        alertController.mainView.alpha = 1.0;
        alertController.mainView.transform = CGAffineTransformMakeScale(1.02, 1.02);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.05 animations:^{
            alertController.mainView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            if (finished) {
                [transitionContext completeTransition:YES];
            }
        }];
    }];
}

- (void)dismissAnimateTransition:(id <UIViewControllerContextTransitioning>)transitionContext {
    ZLAlert *alertController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        alertController.mainView.alpha = 0.0;
        alertController.mainView.transform = CGAffineTransformMakeScale(0.9, 0.9);
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
}

@end
